package com.cssw.fyzb.tps.client;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cssw.fyzb.tps.config.live.TxLive;
import com.cssw.fyzb.tps.model.vo.OptLiveStreamVo;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.live.v20180801.models.*;
import lombok.Getter;
import lombok.Setter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;


/**
 * @author Feng Chen
 */
@Setter
@Getter
@Component
public class LiveClient {

    @Autowired
    private TxLive txLive;

    @Value("${live.secretId}")
    private String secretId;

    @Value("${live.secretKey}")
    private String secretKey;

    @Value("${live.endpoint}")
    private String endpoint;

    private com.tencentcloudapi.live.v20180801.LiveClient delegate;

    private static final Logger logger = LoggerFactory.getLogger(LiveClient.class);
    private static final DateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS Z");

    @PostConstruct
    public void start() {
        Credential credential = new Credential(secretId, secretKey);
        HttpProfile httpProfile = new HttpProfile();
        httpProfile.setEndpoint(endpoint);
        ClientProfile clientProfile = new ClientProfile();
        clientProfile.setHttpProfile(httpProfile);
        delegate = new com.tencentcloudapi.live.v20180801.LiveClient(credential, "", clientProfile);
    }

    /**
     * 断开直播流
     *
     * @param app    推流路径
     * @param stream 推流名称
     * @return
     */
    public OptLiveStreamVo dropLiveStream(String app, String stream) {
        OptLiveStreamVo vo = new OptLiveStreamVo();
        try {
            DropLiveStreamRequest request = new DropLiveStreamRequest();
            request.setDomainName(txLive.getPushDomain());
            request.setAppName(app);
            request.setStreamName(stream);
            DropLiveStreamResponse response = delegate.DropLiveStream(request);
            vo.setRequestId(response.getRequestId());
        } catch (TencentCloudSDKException e) {
            logger.error("", e);
            vo.setErrCode(e.getErrorCode());
            vo.setErrMsg(e.getMessage());
            vo.setRequestId(e.getRequestId());
        }
        return vo;
    }

    /**
     * 恢复直播流
     *
     * @param app    推流路径
     * @param stream 推流名称
     * @return
     */
    public OptLiveStreamVo resumeLiveStream(String app, String stream) {
        OptLiveStreamVo vo = new OptLiveStreamVo();
        try {
            ResumeLiveStreamRequest request = new ResumeLiveStreamRequest();
            request.setDomainName(txLive.getPushDomain());
            request.setAppName(app);
            request.setStreamName(stream);
            ResumeLiveStreamResponse response = delegate.ResumeLiveStream(request);
            vo.setRequestId(response.getRequestId());
        } catch (TencentCloudSDKException e) {
            logger.error("", e);
            vo.setRequestId(e.getRequestId());
            vo.setErrCode(e.getErrorCode());
            vo.setErrMsg(e.getMessage());
        }
        return vo;
    }

    /**
     * @param app    推流路径
     * @param stream 推流名称
     * @param day    禁播时间，默认七天, 最长支持 90 天
     * @param reason 原因
     * @return
     */
    public OptLiveStreamVo forbidLiveStream(String app, String stream, Integer day, String reason) {
        OptLiveStreamVo vo = new OptLiveStreamVo();
        try {
            ForbidLiveStreamRequest request = new ForbidLiveStreamRequest();
            request.setDomainName(txLive.getPushDomain());
            request.setAppName(app);
            request.setStreamName(stream);
            request.setResumeTime(DATE_FORMAT.format(getDate(day)));
            request.setReason(reason);
            ForbidLiveStreamResponse response = delegate.ForbidLiveStream(request);
            vo.setRequestId(response.getRequestId());
        } catch (TencentCloudSDKException e) {
            logger.error("", e);
            vo.setRequestId(e.getRequestId());
            vo.setErrCode(e.getErrorCode());
            vo.setErrMsg(e.getMessage());
        }
        return vo;
    }

    /**
     * 创建混流
     *
     * @param params 参数 {"output_stream_id": "xxxx","input_stream_list": [{"input_stream_id": "xxx",	"layout_params": {"image_layer": 1,"input_type": 1,"image_width": 600,"image_height": 600,"location_x": 0,"location_y":0},...}]}
     * @return
     */
    public OptLiveStreamVo createMixLiveStream(String liveId, String params) {
        OptLiveStreamVo vo = new OptLiveStreamVo();
        CreateCommonMixStreamRequest request = new CreateCommonMixStreamRequest();

        JSONObject objects = JSON.parseObject(params);
        JSONObject object = objects.getJSONObject("interface").getJSONObject("para");

        request.setInputStreamList(inputStreamList(object.getJSONArray("input_stream_list")));
        request.setOutputParams(outputParam(object.getString("output_stream_id")));
        request.setMixStreamSessionId(liveId);
        try {
            CreateCommonMixStreamResponse response = delegate.CreateCommonMixStream(request);
            vo.setRequestId(response.getRequestId());
        } catch (TencentCloudSDKException e) {
            logger.error("", e);
            vo.setRequestId(e.getRequestId());
            vo.setErrCode(e.getErrorCode());
            vo.setErrMsg(e.getMessage());
        }
        return vo;
    }

    /**
     * 取消混流
     *
     * @param liveId 房间编号
     * @return
     */
    public OptLiveStreamVo cancelMixLiveStream(String liveId) {
        OptLiveStreamVo vo = new OptLiveStreamVo();
        CancelCommonMixStreamRequest request = new CancelCommonMixStreamRequest();
        request.setMixStreamSessionId(liveId);

        try {
            CancelCommonMixStreamResponse response = delegate.CancelCommonMixStream(request);
            vo.setRequestId(response.getRequestId());
        } catch (TencentCloudSDKException e) {
            logger.error("", e);
            vo.setRequestId(e.getRequestId());
            vo.setErrCode(e.getErrorCode());
            vo.setErrMsg(e.getMessage());
        }
        return vo;
    }

    private CommonMixOutputParams outputParam(String stream) {
        CommonMixOutputParams outputParams = new CommonMixOutputParams();
        outputParams.setOutputStreamName(stream);
        return outputParams;
    }

    private Date getDate(Integer resumeTime) {
        if (resumeTime == null) {
            resumeTime = 7;
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.add(Calendar.DATE, resumeTime);
        return calendar.getTime();
    }

    private CommonMixInputParam[] inputStreamList(JSONArray array) {
        // canvas、mainstream、substream
        CommonMixInputParam[] param = new CommonMixInputParam[array.size()];
        for (int i = 0; i < array.size(); i++) {
            JSONObject object = array.getJSONObject(i);
            param[i] = inputSteam(object);
        }
        return param;
    }

    private CommonMixInputParam inputSteam(JSONObject object) {
        CommonMixInputParam param = new CommonMixInputParam();

        // 流
        param.setInputStreamName(object.getString("input_stream_id"));

        // 参数
        param.setLayoutParams(layoutParam(object.getJSONObject("layout_params")));
        return param;
    }

    private CommonMixLayoutParams layoutParam(JSONObject object) {
        CommonMixLayoutParams layoutParams = new CommonMixLayoutParams();

        layoutParams.setImageLayer(object.getLong("image_layer"));
        if (object.containsKey("input_type")) {
            layoutParams.setInputType(object.getLong("input_type"));
        }

        if (object.containsKey("image_width")) {
            layoutParams.setImageWidth(object.getFloat("image_width"));
        }

        if (object.containsKey("image_height")) {
            layoutParams.setImageHeight(object.getFloat("image_height"));
        }

        if (object.containsKey("location_x")) {
            layoutParams.setLocationX(object.getFloat("location_x"));
        }

        if (object.containsKey("location_y")) {
            layoutParams.setLocationY(object.getFloat("location_y"));
        }

        return layoutParams;
    }

    public static void main(String[] args) {
        LiveClient liveClient = new LiveClient();
        liveClient.setSecretId("AKID61kDTkmaAUZPzVnrfEbkfLvHZdU8nidU");
        liveClient.setSecretKey("sTpwqW1GUTFjxxhCe2B4i6F8l8RSDixx");
        liveClient.setEndpoint("live.tencentcloudapi.com");
        liveClient.start();

//        liveClient.dropLiveStream("77776.livepush.myqcloud.com", "test", "1001");

    }

}
